// 常亮值
const READ_RESTRICT_PATH_LOCK = "path"; // 锁类型，按路径上锁
const SESSION_STORAGE_KEY = 'read_restrict_lock_pass'; // 校验通过标识
const SESSION_STORAGE_VALUE = 'true'; // 校验通过标识
const SESSION_STORAGE_TTL = 5 * 60 * 1000; // 过期时间
const DEFAULT_PWD = "123qwe"; // 默认密码

/**
 * 锁界面代码
 *
 * @param checkType
 * @returns {string}
 */
function lockInterfaceHtml(currentPathTag, pwdValue){
    let html = "" +
        "<div class=\"lock-interface-container\">" +
        "   <div class=\"interface-box\">" +
        "       <div class=\"interface-head-box\">" +
        "           <span>访问密码锁</span>" +
        "           <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1024 1024\" fill=\"currentColor\" aria-label=\"lock icon\">" +
        "               <path d=\"M787.168 952.268H236.832c-30.395 0-55.033-24.638-55.033-55.033V429.45c0-30.395 24.638-55.034 55.033-55.034h82.55V264.35c0-106.38 86.238-192.618 192.618-192.618S704.618 157.97 704.618 264.35v110.066h82.55c30.395 0 55.033 24.639 55.033 55.034v467.785c0 30.395-24.639 55.033-55.033 55.033zM484.483 672.046v115.122h55.034V672.046c31.99-11.373 55.033-41.605 55.033-77.496 0-45.592-36.958-82.55-82.55-82.55s-82.55 36.958-82.55 82.55c0 35.89 23.042 66.123 55.033 77.496zM622.067 264.35c0-60.788-49.28-110.067-110.067-110.067s-110.067 49.28-110.067 110.067v110.066h220.135V264.35z\"></path>" +
        "           </svg>" +
        "       </div>" +
        "       <div class=\"interface-input-box\">" +
        "           <input id=\"pwd\" type=\"password\" placeholder=\"输入访问密码\">" +
        "       </div>" +
        "       <div class='interface-btn-box'>" +
        "           <button type=\"button\" onclick=\"submitReadRestrictCheck('" + currentPathTag + "','" + pwdValue + "')\">确定</button>" +
        "       </div>" +
        "   </div>" +
        "</div>";
    return html;
}

/**
 * 获取配置信息
 *
 * readRestrict: {
 *     type: READ_RESTRICT_PATH_LOCK
 * },
 *
 * @param currentPathTag
 * @returns {*}
 */
function getDocsifyConfig(currentPathTag) {
    let readRestrict = window.$docsify.readRestrictConfig || { key: SESSION_STORAGE_KEY, val: SESSION_STORAGE_VALUE, ttl: SESSION_STORAGE_TTL };
    if (!readRestrict.key) {
        readRestrict.key = SESSION_STORAGE_KEY;
    }
    // 是否开启按路径锁
    // readRestrict.type = READ_RESTRICT_PATH_LOCK;
    if (readRestrict.type === READ_RESTRICT_PATH_LOCK) {
        readRestrict.key = currentPathTag;
    }
    if (!readRestrict.val) {
        readRestrict.val = SESSION_STORAGE_VALUE;
    }
    if (!readRestrict.ttl) {
        readRestrict.ttl = SESSION_STORAGE_TTL;
    }
    return readRestrict;
}

/**
 * 设置带有过期时间的 sessionStorage 项
 *
 * @param key 键, pass
 * @param value 值,
 * @param ttl 过期时间（单位：毫秒）
 */
function setExpiry(key, value, ttl) {
    let now = new Date();
    let item = { value: value, expiry: now.getTime() + ttl,};
    sessionStorage.setItem(key, JSON.stringify(item));
}

/**
 * 获取 sessionStorage 项，检查其是否过期
 *
 * @param key
 * @returns {*|null}
 */
function getExpiry(key) {
    let sessionStorageData = sessionStorage.getItem(key);
    if (!sessionStorageData) {
        return null;
    }
    let dataObject = JSON.parse(sessionStorageData);
    let now = new Date();
    if (now.getTime() > dataObject.expiry) {
        sessionStorage.removeItem(key);
        return null;
    }
    return dataObject.value;
}

/**
 * 提交阅读限制校验
 */
function submitReadRestrictCheck(currentPathTag, pwdValue){
    let inputElement = document.getElementById('pwd');
    let inputValue = inputElement.value;
    if (inputValue != pwdValue) {
        // md5(inputElement.value)
        alert("访问密码错误 ~~~");
        return;
    }
    let docsifyConfig = this.getDocsifyConfig(currentPathTag);
    this.setExpiry(docsifyConfig.key, docsifyConfig.val, docsifyConfig.ttl);
    alert("验证成功 ~");
    window.location.reload();
}

/**
 * 载入插件
 *
 * @type {*[]}
 */
window.$docsify.plugins = [].concat(function(hook, vm) {

    // 钩子函数：每次开始解析 Markdown 内容时调用
    hook.beforeEach(function(content) {
        // const h = window.location.href;
        // 是否开启文章阅读验证  <!-- read_lock: xxx --> 和 <!-- read_lock:xxx -->
        let match;
        const regex = /<!--\s*read_lock:\s*(\w+)\s*-->/;
        // var regex = /<!--\s*read_lock:\s*(\w+)\s*-->/g;
        if (content && (match = content.match(regex))) {
            let path = vm.route.path;
            let docsifyConfig = this.getDocsifyConfig(path);
            var variable0 = match[0];
            var variable1 = match[1]; // xxx  自定义密码
            let pwd = DEFAULT_PWD;
            if (variable1) {
                pwd = variable1; // 自定义密码
            }
            console.log("Variable:", variable0, variable1, path, docsifyConfig, pwd);
            let lockResult = this.getExpiry(docsifyConfig.key);
            if (lockResult != SESSION_STORAGE_VALUE) {
                content = this.lockInterfaceHtml(path, pwd);
            }
        }
        return content;
    });

}, window.$docsify.plugins);